package com.alvis.media.controller.admin;

import com.alvis.media.base.BaseApiController;
import com.alvis.media.base.RestResponse;
import com.alvis.media.domain.User;
import com.alvis.media.domain.VideoPlay;
import com.alvis.media.service.UserService;
import com.alvis.media.service.VideoPlayService;
import com.alvis.media.viewmodel.admin.dashboard.IndexVM;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.Properties;

@RestController("AdminDashboardController")
@RequestMapping(value = "/api/admin/dashboard")
@AllArgsConstructor
public class DashboardController extends BaseApiController {

//    @RequestMapping(value = "/index", method = RequestMethod.POST)
//    public RestResponse<IndexVM> Index() {
//        IndexVM vm = new IndexVM();
//
//
//        return RestResponse.ok(vm);
//    }

    /**
     * 用户Service
     */
    @Autowired
    private UserService userService;

    /**
     * 视频播放Service
     */
    private VideoPlayService videoPlayService;

    /**
     * 首页
     */
    @RequestMapping(value = "/index", method = RequestMethod.POST)
    public RestResponse<IndexVM> Index()
    {
        IndexVM vm = new IndexVM();

        // 查询本月新增用户总数
        int userCount = userService.selectUserCount(new User());
        vm.setNewUserCount(userCount); // 将“本月新增用户总数”返回给首页页面

        // 本月最佳影片
        String bestFilmName = videoPlayService.findBestVideo(new VideoPlay());
        vm.setHotVideoCount(bestFilmName);

        invokePythonVisualize();
        return RestResponse.ok(vm);
    }

    /**
     *  项目中调用Python代码
     */
    public void invokePythonVisualize()
    {
        BufferedReader reader = null;
        InputStream inputStream = null;

        try
        {
            // 1. 加载配置文件
            Properties properties = new Properties();
            // 配置文件放在resources目录下，使用类加载器读取
            inputStream = getClass().getClassLoader().getResourceAsStream("python-config.properties");
            if (inputStream == null)
            {
                throw new FileNotFoundException("配置文件 python-config.properties 未找到");
            }
            properties.load(inputStream);

            // 2. 从配置文件获取路径
            String pythonInterpreter = properties.getProperty("python.interpreter.path");
            String pythonScript = properties.getProperty("python.script.path");

            // 3. 定义命令数组
            String[] cmd = {pythonInterpreter, pythonScript};

            // 4. 启动进程执行命令
            Process process = new ProcessBuilder(cmd)
                    .redirectErrorStream(true)  // 合并错误流到输入流
                    .start();

            // 5. 读取Python的输出
            reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream())
            );

            String line;
            while ((line = reader.readLine()) != null)
            {
                System.out.println("Python输出：" + line);
            }

            // 6. 等待脚本执行完成
            int exitCode = process.waitFor();
            System.out.println("脚本执行结束，退出码：" + exitCode);


        } catch (Exception e) {
            e.printStackTrace();
        }finally
        {
            closeAll(inputStream,reader);
        }
    }

    /**
     *  关闭所有的流资源
     */
    public void closeAll(InputStream inputStream, BufferedReader reader)
    {
        // 关闭资源
        if (reader != null)
        {
            try
            {
                reader.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }

            try
            {
                inputStream.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}
